import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { ElMessage } from 'element-plus'
import { useDataSetStore } from './dataSet'

// 模拟API延迟
const delay = (ms) => new Promise((resolve) => setTimeout(resolve, ms))

// 字段类型选项
export const fieldTypeOptions = [
  { value: 'int', label: '整型' },
  { value: 'float', label: '浮点型' },
  { value: 'string', label: '字符串' },
  { value: 'datetime', label: '日期时间' },
  { value: 'boolean', label: '布尔值' },
  { value: 'json', label: 'JSON' },
]

export const useDataFieldStore = defineStore('dataField', () => {
  // 获取数据集 store
  const dataSetStore = useDataSetStore()

  // 状态
  const fields = ref([])
  const fieldChanges = ref([])
  const loading = ref(false)

  // 初始化一些示例字段数据
  const initSampleData = async () => {
    loading.value = true
    await delay(500)

    // 确保数据集已加载
    await dataSetStore.fetchDatasets()

    fields.value = [
      {
        id: 1,
        datasetId: 1,
        name: 'user_id',
        displayName: '用户ID',
        type: 'int',
        isPrimaryKey: true,
        isNullable: false,
        description: '用户唯一标识',
        synonyms: ['ID', '用户编号'],
        businessTerms: ['用户标识符'],
        createTime: '2023-01-15 10:30:00',
        updateTime: '2023-05-10 16:45:00',
      },
      {
        id: 2,
        datasetId: 1,
        name: 'username',
        displayName: '用户名',
        type: 'string',
        isPrimaryKey: false,
        isNullable: false,
        description: '用户登录名',
        synonyms: ['登录名', '账号'],
        businessTerms: ['账号名称'],
        createTime: '2023-01-15 10:30:00',
        updateTime: '2023-05-10 16:45:00',
      },
      {
        id: 3,
        datasetId: 1,
        name: 'create_time',
        displayName: '创建时间',
        type: 'datetime',
        isPrimaryKey: false,
        isNullable: false,
        description: '用户创建时间',
        synonyms: ['注册时间'],
        businessTerms: ['创建时间戳'],
        createTime: '2023-01-15 10:30:00',
        updateTime: '2023-01-15 10:30:00',
      },
      {
        id: 4,
        datasetId: 2,
        name: 'order_id',
        displayName: '订单ID',
        type: 'int',
        isPrimaryKey: true,
        isNullable: false,
        description: '订单唯一标识',
        synonyms: ['订单编号'],
        businessTerms: ['订单标识符'],
        createTime: '2023-02-10 14:20:00',
        updateTime: '2023-02-10 14:20:00',
      },
      {
        id: 5,
        datasetId: 2,
        name: 'order_amount',
        displayName: '订单金额',
        type: 'float',
        isPrimaryKey: false,
        isNullable: false,
        description: '订单总金额',
        synonyms: ['金额', '总价'],
        businessTerms: ['交易金额'],
        createTime: '2023-02-10 14:20:00',
        updateTime: '2023-06-15 09:30:00',
      },
    ]

    // 初始化字段变更历史
    fieldChanges.value = [
      {
        id: 1,
        fieldId: 2,
        changeType: 'update',
        fieldName: 'username',
        changeDetail: '更新了显示名称和描述',
        oldValue: JSON.stringify({
          displayName: '登录名',
          description: '系统登录用户名',
        }),
        newValue: JSON.stringify({
          displayName: '用户名',
          description: '用户登录名',
        }),
        changeTime: '2023-05-10 16:45:00',
        changedBy: 'admin',
      },
      {
        id: 2,
        fieldId: 5,
        changeType: 'update',
        fieldName: 'order_amount',
        changeDetail: '添加了同义词和业务术语',
        oldValue: JSON.stringify({
          synonyms: ['金额'],
          businessTerms: [],
        }),
        newValue: JSON.stringify({
          synonyms: ['金额', '总价'],
          businessTerms: ['交易金额'],
        }),
        changeTime: '2023-06-15 09:30:00',
        changedBy: 'admin',
      },
    ]

    loading.value = false
  }

  // 获取字段列表
  const fetchFields = async () => {
    if (fields.value.length === 0) {
      await initSampleData()
    }
    return fields.value
  }

  // 获取指定数据集的字段
  const getFieldsByDatasetId = async (datasetId) => {
    await fetchFields()
    return fields.value.filter((field) => field.datasetId === datasetId)
  }

  // 获取单个字段
  const getFieldById = (id) => {
    return fields.value.find((field) => field.id === id)
  }

  // 更新字段
  const updateField = async (id, fieldData) => {
    loading.value = true
    await delay(800)

    const index = fields.value.findIndex((field) => field.id === id)
    if (index !== -1) {
      const oldField = { ...fields.value[index] }
      const updateTime = new Date().toLocaleString()

      fields.value[index] = {
        ...oldField,
        ...fieldData,
        updateTime,
      }

      // 记录变更历史
      const changeDetail = Object.keys(fieldData)
        .filter((key) => JSON.stringify(oldField[key]) !== JSON.stringify(fieldData[key]))
        .map((key) => `更新了${key}`)
        .join('，')

      if (changeDetail) {
        const changedKeys = Object.keys(fieldData).filter(
          (key) => JSON.stringify(oldField[key]) !== JSON.stringify(fieldData[key]),
        )

        const oldValue = {}
        const newValue = {}

        changedKeys.forEach((key) => {
          oldValue[key] = oldField[key]
          newValue[key] = fieldData[key]
        })

        fieldChanges.value.push({
          id: fieldChanges.value.length + 1,
          fieldId: id,
          changeType: 'update',
          fieldName: oldField.name,
          changeDetail,
          oldValue: JSON.stringify(oldValue),
          newValue: JSON.stringify(newValue),
          changeTime: updateTime,
          changedBy: 'current_user', // 实际项目中应该从认证信息获取
        })
      }

      loading.value = false
      ElMessage.success('字段更新成功')
      return fields.value[index]
    }

    loading.value = false
    ElMessage.error('未找到字段')
    return null
  }

  // 获取字段的变更历史
  const getFieldChangeHistory = (fieldId) => {
    return fieldChanges.value
      .filter((change) => change.fieldId === fieldId)
      .sort((a, b) => new Date(b.changeTime) - new Date(a.changeTime))
  }

  // 根据ID获取数据集名称
  const getDatasetName = (datasetId) => {
    const dataset = dataSetStore.getDatasetById(datasetId)
    return dataset ? dataset.name : '未知数据集'
  }

  // 计算属性
  const fieldOptions = computed(() => {
    return fields.value.map((field) => ({
      value: field.id,
      label: `${field.displayName || field.name} (${getDatasetName(field.datasetId)})`,
      datasetId: field.datasetId,
    }))
  })

  // 根据数据集ID获取字段选项
  const getFieldOptionsByDatasetId = (datasetId) => {
    return fields.value
      .filter((field) => field.datasetId === datasetId)
      .map((field) => ({
        value: field.id,
        label: field.displayName || field.name,
      }))
  }

  return {
    fields,
    fieldChanges,
    loading,
    fetchFields,
    getFieldsByDatasetId,
    getFieldById,
    updateField,
    getFieldChangeHistory,
    fieldOptions,
    getFieldOptionsByDatasetId,
  }
})
